package com.itheima.reggie.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.DishDto;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.entity.DishFlavor;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.service.DishFlavorService;
import com.itheima.reggie.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/dish")
@Slf4j
public class DishController {


    @Autowired
    private CategoryService categoryService;
    @Autowired
    private DishService dishService;
    @Autowired
    private DishFlavorService dishFlavorService;

//新增菜品
    @PostMapping
  public R<String>save(@RequestBody DishDto dishDto)
  {
      dishService.saveWithFlavor(dishDto);
      return R.success("添加菜品信息成功");
  }



    //分页查询（菜品管理
    @GetMapping("/page")
    public R<Page>page(int page,int pageSize,String name)
    {
        Page<Dish> pageInfo=new Page<>(page,pageSize);
        LambdaQueryWrapper<Dish>lqw=new LambdaQueryWrapper<>();

        lqw.like(name!=null,Dish::getName,name);
        lqw.orderByDesc(Dish::getUpdateTime);
        dishService.page(pageInfo,lqw);

        Page<DishDto> dtoPage=new Page<>();
        BeanUtils.copyProperties(pageInfo,dtoPage,"records");

        List<Dish> records = pageInfo.getRecords();//获取分页查询的数据
        List<DishDto>dtoList=new ArrayList<>();//存放每一条菜品信息的对象

        records.forEach(dish -> {//对单个数据进行处理，Dish实体类中没有categoryName属性 DishDto中有categoryName属性
            DishDto dto=new DishDto();
            BeanUtils.copyProperties(dish,dto);//将遍历单个对象数据复制到dto

            Category byId = categoryService.getById(dish.getCategoryId());//根据categoryId属性获取单个菜品对象
            dto.setCategoryName(byId.getName());//根据单个菜品对象获取CategoryName属性并添加至dto
            dtoList.add(dto);//将dto添加到存放数据对象的集合中


        });
        dtoPage.setRecords(dtoList);//将数据添加回
        return R.success(dtoPage);

    }

    //修改菜品数据回显
    @GetMapping("/{id}")
    public R<DishDto> get(@PathVariable Long id)
    {
        DishDto byIdWithFlavor = dishService.getByIdWithFlavor(id);
        return R.success(byIdWithFlavor);
    }


    //修改菜品
    //
    @PutMapping
    public R<String> update(@RequestBody DishDto dishDto)
    {
        dishService.updateWithFlavor(dishDto);
        return R.success("修改成功");
    }

    //根据分类Id查询菜品信息（
    @GetMapping("/list")
    public R<List<DishDto>> list(Dish dish){
        //构造查询条件
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(dish.getCategoryId() != null ,Dish::getCategoryId,dish.getCategoryId());
        //添加条件，查询状态为1（起售状态）的菜品
        queryWrapper.eq(Dish::getStatus,1);
        //添加排序条件
        queryWrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);

        List<Dish> list = dishService.list(queryWrapper);

        List<DishDto> dishDtoList = list.stream().map((item) -> {
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(item,dishDto);

            Long categoryId = item.getCategoryId();//分类id
            //根据id查询分类对象
            Category category = categoryService.getById(categoryId);
            if(category != null){
                String categoryName = category.getName();
                dishDto.setCategoryName(categoryName);
            }

            //当前菜品的id
            Long dishId = item.getId();
            LambdaQueryWrapper<DishFlavor> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(DishFlavor::getDishId,dishId);
            //SQL:select * from dish_flavor where dish_id = ?
            List<DishFlavor> dishFlavorList = dishFlavorService.list(lambdaQueryWrapper);
            dishDto.setFlavors(dishFlavorList);

            return dishDto;
        }).collect(Collectors.toList());

        return R.success(dishDtoList);
    }










}
